package part2.miniTomcat;

import part2.miniTomcat.request.Request;
import part2.miniTomcat.request.RequestFacade;
import part2.miniTomcat.request.Response;
import part2.miniTomcat.request.ResponseFacade;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

/**
 * @author 大忽悠
 * @create 2022/9/1 20:40
 */
public class ServletProcessor {
    private URLClassLoader classLoader;

    public ServletProcessor() throws IOException {
        URL[] urls = new URL[1];
        URLStreamHandler urlStreamHandler=null;
        //类路径
        File classPath=new File(Server.WEB_ROOT);
        //资源仓库地址
        //file.getCanonicalPath: 返回标准的文件绝对路径
        //URL : 参数一: 资源协议--file,https,ftp等 参数二:主机名,http是需要 参数三:资源路径,这里填文件路径
        String respository=(new URL("file",null,classPath.getCanonicalPath()+File.separator)).toString();
        System.out.println("仓库地址为: "+respository);
        // urlStreamHandler通过资源不同的来源来决定处理的逻辑--->不同前缀来识别。比如："file :"、"http :"、"jar :"
        urls[0] = new URL(null, respository, urlStreamHandler);
        //加载指定路径下的class
        classLoader=new URLClassLoader(urls);
    }

    public void process(Request request, Response response) {
        try {
            //获取servlet的名字
            String uri = request.getUri();
            String servletName = uri.substring(uri.lastIndexOf("/") + 1);
            System.out.println("Servlet的名字为: "+servletName);

            //填写全类名
            Class servletClass = classLoader.loadClass(servletName);

            Servlet servlet=null;
            servlet = (Servlet) servletClass.newInstance();
            //执行指定servlet的方法
            servlet.service((ServletRequest) new RequestFacade(request),(ServletResponse) new ResponseFacade(response));
        } catch (IOException | ClassNotFoundException | IllegalAccessException | InstantiationException | ServletException e) {
            e.printStackTrace();
        }
    }
}
